package com.breakfast.fun.ui.user;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.breakfast.fun.Constant;
import com.breakfast.fun.R;
import com.breakfast.fun.adapter.user.UserGridAdapter;
import com.breakfast.fun.base.BaseFragment;
import com.breakfast.fun.dao.AddressDao;
import com.breakfast.fun.dao.DaoMaster;
import com.breakfast.fun.dao.GoodCartDao;
import com.breakfast.fun.dao.ProductCartDao;
import com.breakfast.fun.data.entity.user.Result;
import com.breakfast.fun.data.entity.user.User;
import com.breakfast.fun.data.entity.user.UserData;
import com.breakfast.fun.data.entity.user.UserGrid;
import com.breakfast.fun.data.entity.user.coupon.Coupon;
import com.breakfast.fun.event.FinishEvent;
import com.breakfast.fun.ui.user.account.UserAccountActivity;
import com.breakfast.fun.ui.user.address.UserAddressActivity;
import com.breakfast.fun.ui.user.cart.UserCartActivity;
import com.breakfast.fun.ui.user.coupon.CouponActivity;
import com.breakfast.fun.ui.user.feedback.FeedBackActivity;
import com.breakfast.fun.ui.user.info.UserInfoActivity;
import com.breakfast.fun.ui.user.invite.UserInviteActivity;
import com.breakfast.fun.ui.user.login.GiftActivity;
import com.breakfast.fun.ui.user.more.MoreActivity;
import com.breakfast.fun.ui.user.order.UserOrderActivity;
import com.breakfast.fun.ui.user.recharge.RechargeActivity;
import com.breakfast.fun.ui.web.WebActivity;
import com.breakfast.fun.util.Api;
import com.breakfast.fun.util.ImageUtil;
import com.breakfast.fun.util.JumpUtil;
import com.breakfast.fun.util.L;
import com.breakfast.fun.util.SharedUtil;
import com.breakfast.fun.util.T;
import com.breakfast.fun.util.TUtil;
import com.breakfast.fun.view.widget.CustomDialog;
import com.breakfast.fun.view.widget.CustomGridView;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;

/**
 * Created by Administrator on 2016/8/22.
 */
public class UserFragment extends BaseFragment<UserPresenter, UserModel> implements UserContract.View {


    @Bind(R.id.iv_user_head)
    ImageView ivUserHead;
    @Bind(R.id.tv_user_name)
    TextView tvUserName;
    @Bind(R.id.rl_user_is_login)
    LinearLayout rlUserIsLogin;
    @Bind(R.id.tv_user_balance)
    TextView tvUserBalance;
    @Bind(R.id.ll_user_balance)
    LinearLayout llUserBalance;
    @Bind(R.id.tv_user_invite)
    TextView tvUserInvite;
    @Bind(R.id.ll_user_invite)
    LinearLayout llUserInvite;
    @Bind(R.id.gv_user)
    CustomGridView gvUser;
    @Bind(R.id.btn_user_login)
    Button btnUserLogin;
    @Bind(R.id.btn_user_exit)
    Button btnUserExit;
    @Bind(R.id.ptrsv_user)
    PullToRefreshScrollView ptrsvUser;
    @Bind(R.id.tv_user_coupon)
    TextView mTvUserCoupon;
    @Bind(R.id.ll_user_coupon)
    LinearLayout mLlUserCoupon;
    private ImageUtil imageUtil;

    private UserGridAdapter userGridAdapter;

    private List<UserGrid> gridList = new ArrayList<>();

    public static boolean isNeedRefesh = false;

    //退出登录弹出框
    private CustomDialog dialog;

    private int curCouponCount = 0;

    int[] gridImageId = new int[]{R.drawable.ic_user_sign, R.drawable.ic_user_lottery, R.drawable.ic_user_order,
            R.drawable.ic_user_cart, R.drawable.ic_user_recharge, R.drawable.ic_user_address, R.drawable.ic_user_feedback, R.drawable.ic_user_phone, R.drawable.ic_user_more};
    /* String[] grideTitle = new String[]{"我的订单", "购物车", "送餐地址", "关于我们", "余额充值",
             "邀请朋友", "服务中心", "客服热线", "意见反馈"};*/
    String[] gridTitle = new String[]{"每日签到", "每日抽奖", "我的订单", "购物车", "余额充值", "送餐地址",
            "意见反馈", "客服热线", "更多"};
    private int curUnPayCount = 0;


    @Override
    public int getLayoutId() {
        return R.layout.fragment_user;
    }

    @Override
    public void initView() {

        imageUtil = new ImageUtil(context);

        for (int i = 0; i < gridImageId.length; i++) {
            UserGrid userGrid = new UserGrid();
            userGrid.setImage(gridImageId[i]);
            userGrid.setTitle(gridTitle[i]);
            gridList.add(userGrid);
        }

        userGridAdapter = new UserGridAdapter(context, gridList);
        gvUser.setAdapter(userGridAdapter);

        setListener();

        ptrsvUser.setOnRefreshListener(refreshView -> {
            if (Constant.getUserData() != null) {
                presenter.getUser();
                presenter.getCouponCount();
            } else {
                ptrsvUser.onRefreshComplete();
                presenter.getCouponCount();
            }
        });


    }

    private void setListener() {
        UserData userData = Constant.getUserData();
        if (userData == null) {
            rlUserIsLogin.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    JumpUtil.toLogin(context);
                }
            });
            btnUserLogin.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    JumpUtil.toLogin(context);
                }
            });
        } else {
            tvUserName.setText(userData.getNickname());
            tvUserBalance.setText("￥" + userData.getMoney());
            tvUserInvite.setText(userData.getInviteCount() + "");
            imageUtil.loadCircleImage(userData.getPhoto(), ivUserHead);
            btnUserLogin.setVisibility(View.GONE);
            btnUserExit.setVisibility(View.VISIBLE);
            btnUserExit.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    dialog = new CustomDialog(UserFragment.this.getActivity(), R.style.dialog_style,
                            R.layout.dialog_custom, "注销提示", "你确定要退出登录吗？", false, false, new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            dialog.dismiss();
                            SharedUtil.putString(context, "user", null);
                            SharedUtil.putString(context, "recommendCode", null);
                            SharedUtil.putString(context, "sign", null);
                            Constant.setUserData(null);
                            Constant.setUserSign(null);
                            ProductCartDao cartDao = DaoMaster.newDevSession(context, "zaofan.db").getProductCartDao();
                            cartDao.deleteAll();
                            AddressDao addressDao = DaoMaster.newDevSession(context, "zaofan.db").getAddressDao();
                            addressDao.deleteAll();
                            GoodCartDao goodCartDao = DaoMaster.newDevSession(context, "zaofan.db").getGoodCartDao();
                            goodCartDao.deleteAll();
                            refreshUser();
                            userGridAdapter = new UserGridAdapter(context, gridList);
                            gvUser.setAdapter(userGridAdapter);
                            ivUserHead.setOnClickListener(v -> {
                                JumpUtil.toLogin(context);
                            });
                        }
                    });
                    dialog.show();
                }
            });


            Glide.with(this).load(userData.getPhoto()).placeholder(R.drawable.ic_user_head)
                    .error(R.drawable.ic_user_head).into(ivUserHead);

            ivUserHead.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(context, UserInfoActivity.class);
                    startActivity(intent);


                }
            });
            rlUserIsLogin.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    Intent intent = new Intent(context, UserInfoActivity.class);
                    startActivity(intent);
                }
            });
        }

        setGridListener();

        llUserBalance.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (Constant.getUserData() == null) {
                    T.show("请登录!");
                    JumpUtil.toLogin(getActivity());
                    return;
                }
                Intent intent = new Intent(getActivity(), UserAccountActivity.class);
                if (Constant.getUserData() != null && Constant.getUserSign() != null) {
                    intent.putExtra("userId", Constant.getUserData().getId() + "");
                    intent.putExtra("userSign", Constant.getUserSign());
                    startActivity(intent);
                } else {
                    T.show("获取数据失败");
                }

            }
        });

        mLlUserCoupon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Constant.getUserData() == null) {
                    T.show("请登录!");
                    JumpUtil.toLogin(getActivity());
                    return;
                }
                Intent intent = new Intent(getActivity(), CouponActivity.class);
                intent.putExtra("isFromUser", true);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            }
        });

        llUserInvite.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (Constant.getUserData() == null) {
                    T.show("请登录!");
                    JumpUtil.toLogin(getActivity());
                    return;
                }
                Intent intent = new Intent(getActivity(), UserInviteActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            }
        });

    }

    private void setGridListener() {
        gvUser.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent = new Intent();
                switch (i) {
                    //每日签到
                    case 0:
                        if (Constant.getUserData() == null) {
                            T.show("请登录!");
                            JumpUtil.toLogin(getActivity());
                            return;
                        }
                        intent.setClass(getActivity(), WebActivity.class);
                        intent.putExtra("title", "每日签到");
                        intent.putExtra("des", "每日签到");
                        intent.putExtra("url", Api.BASE_URL + "fe/user/apphtml/sign_daily/sign_daily.html");
                        startActivity(intent);
                        break;
                    //每日抽奖
                    case 1:
                        if (Constant.getUserData() == null) {
                            T.show("请登录!");
                            JumpUtil.toLogin(getActivity());
                            return;
                        }
                        intent.setClass(getActivity(), WebActivity.class);
                        intent.putExtra("title", "每日抽奖");
                        intent.putExtra("des", "每日抽奖");
                        intent.putExtra("url", Api.BASE_URL + "fe/user/apphtml/lottery/turnplate.html");
                        startActivity(intent);
                        break;
                    //我的订单
                    case 2:
                        if (Constant.getUserData() == null) {
                            T.show("请登录!");
                            JumpUtil.toLogin(getActivity());
                            return;
                        }
                        intent.setClass(getActivity(), UserOrderActivity.class);
                        startActivity(intent);
                        break;
                    //购物车
                    case 3:
                        intent.setClass(getActivity(), UserCartActivity.class);
                        startActivity(intent);
                        break;
                    //余额充值
                    case 4:
                        if (Constant.getUserData() == null) {
                            T.show("请登录!");
                            JumpUtil.toLogin(getActivity());
                            return;
                        }

                        intent.setClass(getActivity(), RechargeActivity.class);
                        startActivity(intent);
                        break;
                    //送餐地址
                    case 5:
                        if (Constant.getUserData() == null) {
                            T.show("请登录!");
                            JumpUtil.toLogin(getActivity());
                            return;
                        }
                        intent.setClass(getActivity(), UserAddressActivity.class);
                        startActivity(intent);
                        break;
                    //意见反馈
                    case 6:
                        if (Constant.getUserData() == null) {
                            T.show("请登录!");
                            JumpUtil.toLogin(context);
                            return;
                        }
                        intent.setClass(context, FeedBackActivity.class);
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);
                        break;
                    //客服热线
                    case 7:
                        Uri uri = Uri.parse("tel:" + Constant.SERVICE_TEL);
                        intent = new Intent(Intent.ACTION_DIAL, uri);
                        startActivity(intent);
                        break;
                    //更多
                    case 8:
                        if (Constant.getUserData() == null) {
                            T.show("请登录!");
                            JumpUtil.toLogin(getActivity());
                            return;
                        }

                        intent.setClass(getActivity(), MoreActivity.class);
                        startActivity(intent);
                        break;
                }
            }
        });
    }

    private void refreshUser() {
        UserData userData = Constant.getUserData();
        if (userData == null) {
            tvUserName.setText("登录/注册");
            tvUserBalance.setText("￥0.00");
            btnUserLogin.setText("登录");
            btnUserLogin.setVisibility(View.VISIBLE);
            btnUserExit.setVisibility(View.GONE);
            tvUserInvite.setText("0");
            mTvUserCoupon.setText("0");
            ivUserHead.setImageResource(R.drawable.ic_user_head);
        } else {
            presenter.getCode();
            presenter.getUnPayCount();
            tvUserName.setText(userData.getNickname());
            tvUserBalance.setText("￥" + userData.getMoney());
            btnUserLogin.setVisibility(View.GONE);
            btnUserExit.setVisibility(View.VISIBLE);
            tvUserInvite.setText(userData.getInviteCount() + "");
            imageUtil.loadCircleImage(userData.getPhoto(), ivUserHead);
        }
        setListener();
    }


    @Override
    public void onResume() {
        super.onResume();
        if (isNeedRefesh) {
            refreshUser();
            isNeedRefesh = false;
        }

        boolean birthdayTipped = SharedUtil.getBoolean(context, "birthdayTipped", false);
        //只提示一次生日信息
        if (!birthdayTipped && Constant.getUserData() != null) {
            //未填写生日信息
            if (null == Constant.getUserData().getBirthday() || "".equals(Constant.getUserData().getBirthday())) {
                dialog = new CustomDialog(UserFragment.this.getActivity(), R.style.dialog_style,
                        R.layout.dialog_custom, "生日信息提示", "还未填写生日信息，现在去填写吗?", false, false, new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        dialog.dismiss();
                        Intent intent = new Intent(context, UserInfoActivity.class);
                        startActivity(intent);
                    }
                });
                dialog.show();
                SharedUtil.putBoolean(context, "birthdayTipped", true);
            }
        }


        //取消订单回到userFragment优惠券刷新\
        presenter.getCouponCount();
        presenter.getUnPayCount();
        userGridAdapter = new UserGridAdapter(context, gridList);
        gvUser.setAdapter(userGridAdapter);
    }


    @Override
    public void saveCode(String code) {
        SharedUtil.putString(context, "recommendCode", code);
    }

    @Override
    public void refresh(User user) {
        Constant.setUserData(user.getData());
        SharedUtil.putString(context, "user", new Gson().toJson(user.getData()));
        refreshUser();
        if (ptrsvUser.isRefreshing()) {
            ptrsvUser.onRefreshComplete();
        }
    }

    @Override
    public void stopRefresh() {
        ptrsvUser.onRefreshComplete();
    }

    @Override
    public void setCouponCount(int couponCount) {
        mTvUserCoupon.setText(couponCount + "");
    }

    @Override
    public void setUnPayCount(int unPayCount) {
        curUnPayCount = unPayCount;
        userGridAdapter.setUnPayCount(unPayCount);
        userGridAdapter.notifyDataSetChanged();
    }

    //    切换底部TAB时购物车参数刷新
    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
//        userGridAdapter = new UserGridAdapter(context, gridList);
        if (userGridAdapter != null) {
            userGridAdapter.setUnPayCount(curUnPayCount);
//        gvUser.setAdapter(userGridAdapter);
            userGridAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }
}
